<!--
 * @Description: 
 * @Date: 2020-12-08 09:32:03
 * @LastEditors: lother
 * @LastEditTime: 2021-01-08 14:44:13
 * @FilePath: \AccounOpening-WEB\src\views\openProcess\config.vue
-->
<template>
<el-card class="box-card configlist">
   <div slot="header" class="clearfix">
      <el-page-header :title="$t('openProcess.config.56cjw0u61v40')" @back="goBack">
        <template slot="content" v-if="
          (checkPermission(['openFlow@update']) && rowItem.id) ||
          (checkPermission(['openFlow@save']) && !rowItem.id)
        ">
             <el-button type="primary" icon="el-icon-video-play" @click="submit">{{$t('openProcess.config.56cjw0u62ug0')}}</el-button>
             <el-button type="danger" class="delete-btn" icon="el-icon-delete"  @click="empty">{{$t('openProcess.config.56cjw0u63500')}}</el-button>
             <p class="title_tip">{{$t('openProcess.config.56cjwkbdgds0')}}</p>
        </template>
      </el-page-header>
      <el-divider></el-divider>
      <el-form :inline="true" :model="formInline" class="demo-form-inline ZmaBt20">
        <el-form-item :label="$t('openProcess.config.56cjw0u63gk0')">
          <el-input v-model="formInline.name_zh" :placeholder="$t('openProcess.config.56cjw0u63yk0')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('openProcess.config.56cjw0u64b00')">
          <el-input v-model="formInline.name_en" :placeholder="$t('openProcess.config.56cjw0u64k80')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('openProcess.config.56gv5u704ws0')">
          <el-input v-model="formInline.name_tc" :placeholder="$t('openProcess.config.56cjw0u64k80')"></el-input>
        </el-form-item>
      </el-form>
  </div>
  <div class="container">
    <div class="left-board">
      <el-scrollbar class="left-scrollbar">
        <div class="components-list">
          <div v-for="(item, listIndex) in leftComponents" :key="listIndex">
            <div class="components-title">
              <svg-icon icon-class="icon-component" />
              {{ item.title }}
            </div>
            <draggable
              class="components-draggable"
              :list="item.list"
              :group="{ name: 'componentsGroup', pull: 'clone', put: false }"
              :clone="cloneComponent"
              draggable=".components-item"
              :sort="false"
              @end="onEnd"
            >
              <div
                v-for="(element, index) in item.list"
                :key="index"
                class="components-item"
                @click="addComponent(element)"
              >
                <div class="components-body">
                  <svg-icon :icon-class="'icon-'+element.tagIcon" />
                  {{ element['title_'+langSuffix] }}
                </div>
              </div>
            </draggable>
          </div>
        </div>
      </el-scrollbar>
    </div>

    <div class="center-board">
      <el-scrollbar class="center-scrollbar">
        <el-row class="center-board-row" :gutter="formConf.gutter">
          <el-form
            :size="formConf.size"
            :label-position="formConf.labelPosition"
            :disabled="formConf.disabled"
            :label-width="formConf.labelWidth + 'px'"
          >
            <draggable class="drawing-board" :list="drawingList" :animation="340" group="componentsGroup">
              <draggable-item
                v-for="(item, index) in drawingList"
                :key="item.renderKey"
                :drawing-list="drawingList"
                :current-item="item"
                :index="index"
                :active-id="activeId"
                :form-conf="formConf"
                @activeItem="activeFormItem"
                @copyItem="drawingItemCopy"
                @deleteItem="drawingItemDelete"
                :lang="langSuffix"
              />
            </draggable>
            <div v-show="!drawingList.length" class="empty-info">
              {{$t('openProcess.config.56cjw0u64so0')}}
            </div>
          </el-form>
        </el-row>
      </el-scrollbar>
    </div>
      <right-panel
      :active-data="activeData"
      :form-conf="formConf"
      :show-field="!!drawingList.length"
      @tag-change="tagChange"
    />
  </div>
</el-card>
</template>

<script>
import draggable from 'vuedraggable'
import { debounce } from 'throttle-debounce'
import { saveAs } from 'file-saver'
import ClipboardJS from 'clipboard'
import render from '@/components/render/render'
import RightPanel from './RightPanel'
import {
  inputComponents, selectComponents, layoutComponents, formConf
} from '@/components/generator/config'
import {
  exportDefault, beautifierConf, isNumberStr, titleCase, deepClone
} from '@/utils/index'
import {
  makeUpHtml, vueTemplate, vueScript, cssStyle
} from '@/components/generator/html'
import { makeUpJs } from '@/components/generator/js'
import { makeUpCss } from '@/components/generator/css'
import drawingDefalut from '@/components/generator/drawingDefalut'
import DraggableItem from './DraggableItem'
import {
  getDrawingList, saveDrawingList, getIdGlobal, saveIdGlobal, getFormConf
} from '@/utils/db'
import loadBeautifier from '@/utils/loadBeautifier'

let beautifier
const emptyActiveData = { style: {}, autosize: {} }
let oldActiveId
let tempActiveData
const drawingListInDB = getDrawingList()
const formConfInDB = getFormConf()
const idGlobal = getIdGlobal()


import { addPage , editPage  , getFlow } from '@/api/openProcess/Hopen'

export default {
  props:{
      list:{
        type:String,
        default:()=>{}
      },
      type:{
        type:[String,Number],
        default:()=>''
      },
      user_type:{
        type:[String,Number],
        default:()=>''
      },
      rowItem:{
        type:Object,
        default:()=>{}
      }
  },
  components: {
    draggable,
    render,
    RightPanel,
    DraggableItem
  },
  data() {
    return {
      formInline:{
        type:'',
        name_zh:"",
        name_en:"",
        name_tc:"",
        user_type :'',
        url_path:''
      },
      idGlobal,
      formConf,
      inputComponents,
      selectComponents,
      layoutComponents,
      labelWidth: 100,
      drawingList: drawingDefalut,
      drawingData: {},
      activeId: '',
      drawerVisible: false,
      formData: {},
      dialogVisible: false,
      jsonDrawerVisible: false,
      generateConf: null,
      showFileName: false,
      activeData: drawingDefalut[0],
      saveDrawingListDebounce: debounce(340, saveDrawingList),
      saveIdGlobalDebounce: debounce(340, saveIdGlobal),
      leftComponents: [
        {
          title: this.$t('openProcess.config.56cjw0u651c0'),
          list: inputComponents
        },
        {
          title: this.$t('openProcess.config.56cjw0u659s0'),
          list: selectComponents
        },
        {
          title: this.$t('openProcess.config.56cjw0u65i80'),
          list: layoutComponents
        }
      ]
    }
  },
  computed: {
    langSuffix(){
      return this.$store.state.settings.langTail;
    },

  },
  watch: {
    // eslint-disable-next-line func-names
    'activeData.title_zh': function (val, oldVal) {
      if (
        this.activeData.placeholder === undefined
        || !this.activeData.tag
        || oldActiveId !== this.activeId
      ) {
        return
      }
      this.activeData.placeholder = this.activeData.placeholder.replace(oldVal, '') + val
    },
    activeId: {
      handler(val) {
        oldActiveId = val
      },
      immediate: true
    },
    drawingList: {
      handler(val) {
        this.saveDrawingListDebounce(val)
        if (val.length === 0) this.idGlobal = 1
      },
      deep: true
    },
    idGlobal: {
      handler(val) {
        this.saveIdGlobalDebounce(val)
      },
      immediate: true
    }
  },
  mounted() {
    if (Array.isArray(drawingListInDB) && drawingListInDB.length > 0) {
      this.drawingList = drawingListInDB
    } else {
      this.drawingList = drawingDefalut
    }
    this.activeFormItem(this.drawingList[0])
    if (formConfInDB) {
      this.formConf = formConfInDB
    }
    loadBeautifier(btf => {
      beautifier = btf
    })
  },
  methods: {
    init(id,type,user_type){
      if(id !==''){
        getFlow(id)
        .then(res=>{
          if(res.code==10000){
            var {name_zh,name_en,name_tc,url_path,page_fields,...rest}  = res.data;
            this.formInline = Object.assign({},this.formInline,{name_zh,name_en,name_tc,url_path,type,user_type});
            var  arr=[]
            if(page_fields.length ==0){
              this.idGlobal=1
            }else{
              this.idGlobalList(arr,page_fields)
              var s =Math.max(...arr) 
              this.idGlobal=Math.max(...arr)  || 1
            }
            this.drawingList = page_fields;
            this.activeData = page_fields.length?page_fields[0]:drawingDefalut[0]
            
          }
        })
      }else{
            this.formInline = Object.assign({},this.formInline,{name_zh:"",name_en:"",name_tc:"",url_path:"",type,user_type});
      }
    },
    idGlobalList(arr,list){
      for (let index = 0; index < list.length; index++) {
        const element = list[index];
        arr.push( Number((element.name).replace(/[^0-9]/ig,"")))
        if(element.type=='row'){
            this.idGlobalList(arr,element.container)
        }else{
          arr.push( Number((element.name).replace(/[^0-9]/ig,"")))
        }
      }
    },
    // 返回时进行清空数据，不进行保留
    goBack() {
        this.$emit("indexBack")
        this.drawingList = []
        this.idGlobal = 1
    },
    submit(){
      if(this.drawingList.length==0){
        this.$message.error(this.$t('openProcess.config.56cjw0u65qo0'));
        return false
      }
      var  arr=[]
      for (let index = 0; index < this.drawingList.length; index++) {
        const element = this.drawingList[index];
        if(!arr.includes(element.name)){
          arr.push(element.name)
        }else{
          this.$message.error(this.$t('openProcess.config.56cjyg5j3e40'+element.name+this.$t('openProcess.config.56cjytvaoc00')));
          this.activeId =  Number((element.name).replace(/[^0-9]/ig,""))
          return false;
        }
      }

      var obj  =  Object.assign({},this.formInline,{fields :this.drawingList})
      if(!this.formInline.name_zh){
        this.$message.error(this.$t('openProcess.config.56cjw0u661w0'));
        return false
      }else if(!this.formInline.name_en){
        this.$message.error(this.$t('openProcess.config.56cjw0u66a00'));
        return false
      }else if(!this.formInline.name_tc){
        this.$message.error(this.$t('openProcess.config.56gv7vwt4no0'));
        return false
      }
      if(this.rowItem.id){
        this.$confirm(this.$t('openProcess.config.56cjw0u66i80'), this.$t('openProcess.config.56cjw0u66qc0'), {
          confirmButtonText: this.$t('openProcess.config.56cjw0u66ys0'),
          cancelButtonText: this.$t('openProcess.config.56cjw0u676o0'),
          type: "warning",
        })
          .then(() => {
            this.editPageList(this.rowItem.id,obj)
            
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: this.$t('openProcess.config.56cjw0u67es0'),
            });
          });
      }else{
        this.addPageList(obj)
      }
    },
    addPageList(obj){
      addPage(obj)
      .then(res=>{
        console.log('2')
        if(res.code==10000){
          this.goBack()
        }
      })
    },
    editPageList(id,obj){
      editPage(id,obj)
      .then(res=>{
        console.log('333')
         if(res.code==10000){
          this.goBack()
        }
      })
    },
    activeFormItem(currentItem) {
      this.activeData = currentItem
      this.activeId = Number((currentItem.name).replace(/[^0-9]/ig,""));
      //  Number((currentItem.name).replace(/[^0-9]/ig,""))
    },
    onEnd(obj) {
      if (obj.from !== obj.to) {
        this.activeData = tempActiveData
        this.activeId = this.idGlobal
      }
    },
    addComponent(item) {
      const clone = this.cloneComponent(item)
      this.drawingList.push(clone)
      this.activeFormItem(clone)
    },
    cloneComponent(origin) {
      const clone = deepClone(origin)
      const config = clone
      config.span = this.formConf.span // 生成代码时，会根据span做精简判断
      this.createIdAndKey(clone)
      clone.placeholder !== undefined && (clone.placeholder += config['title_'+this.langSuffix])
      tempActiveData = clone
      return tempActiveData
    },
    createIdAndKey(item) {
      const config = item
      config.formId = ++this.idGlobal
      config.renderKey = `${config.formId}${+new Date()}` // 改变renderKey后可以实现强制更新组件
      if (config.layout === 'colFormItem') {
        item.name = `field${this.idGlobal}`
      } else if (config.layout === 'rowFormItem') {
        config.name = `row${this.idGlobal}`
        !Array.isArray(config.container) && (config.container = [])
        delete config.label // rowFormItem无需配置label属性
      }
      if (Array.isArray(config.container)) {
        config.container = config.container.map(childItem => this.createIdAndKey(childItem))
      }
      return item
    },
    generate(data) {
      const func = this[`exec${titleCase(this.operationType)}`]
      this.generateConf = data
      func && func(data)
    },
    empty() {
      this.$confirm(this.$t('openProcess.config.56cjw0u67nk0'), this.$t('openProcess.config.56cjw0u66qc0'), { type: 'warning' }).then(
        () => {
          this.drawingList = []
          this.idGlobal = 1
        }
      )
    },
    drawingItemCopy(item, list) {
      let clone = deepClone(item)
      clone = this.createIdAndKey(clone)
      list.push(clone)
      this.activeFormItem(clone)
    },
    drawingItemDelete(index, list) {
      this.$confirm(this.$t('openProcess.config.56cjw0u67xk0'), this.$t('openProcess.config.56cjw0u66qc0'), {
          confirmButtonText: this.$t('openProcess.config.56cjw0u66ys0'),
          cancelButtonText: this.$t('openProcess.config.56cjw0u676o0'),
          type: 'warning'
        }).then(() => {
          list.splice(index, 1)
          this.$nextTick(() => {
            const len = this.drawingList.length
            if (len) {
              this.activeFormItem(this.drawingList[len - 1])
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('openProcess.config.56cjw0u684g0')
          });          
        });

      
    },
    tagChange(newTag) {
      newTag = this.cloneComponent(newTag)
      const config = newTag
      newTag.name = this.activeData.name
      config.formId = this.activeId
      config.span = this.activeData.span
      this.activeData.tag = config.tag
      this.activeData.tagIcon = config.tagIcon
      this.activeData.document = config.document
      if (typeof this.activeData.defaultValue === typeof config.defaultValue) {
        config.defaultValue = this.activeData.defaultValue
      }
      Object.keys(newTag).forEach(key => {
        if (this.activeData[key] !== undefined) {
          newTag[key] = this.activeData[key]
        }
      })
      this.activeData = newTag
      this.updateDrawingList(newTag, this.drawingList)
    },
    updateDrawingList(newTag, list) {
      const index = list.findIndex(item => item.formId === this.activeId)
      if (index > -1) {
        list.splice(index, 1, newTag)
      } else {
        list.forEach(item => {
          if (Array.isArray(item.container)) this.updateDrawingList(newTag, item.container)
        })
      }
    },
    refreshJson(data) {
      this.drawingList = deepClone(data.fields)
      delete data.fields
      this.formConf = data
    }
  }
}
</script>

<style lang='scss' scoped>
@import '@/styles/index.scss';
@import '@/styles/home';
.configlist{
  
  >>>.el-radio-group{
    padding:6px  0;
    line-height: inherit;
    .el-radio{
      width: 100%;
      white-space: inherit;
      line-height: 24px;
    }
  }
  >>>.el-checkbox-group{
    padding:6px  0;
    line-height: inherit;
    .el-checkbox{
      white-space: inherit;
      width: 100%;
      line-height: 24px;
    }
  }
}
.title_tip{
  font-size: 14px;
  display: block;
  padding-top: 15px;
  line-height: 20px;
  color: red;
}
>>>.el-page-header__left{
  width: 95px;
}
>>>.el-page-header__content{
  width: calc( 100% -  140px );
}
</style>
